<script lang="ts" setup>
import { getRuleListAPI } from '@/apis/card';
import type { Rule, RuleListParams } from '@/types/card';
import { ref } from 'vue';
import { utils, writeFileXLSX } from 'xlsx';

const ruleList = ref<Rule[]>([])
const params = ref<RuleListParams>({
  page: 1,
  pageSize: 10
})
const total = ref(0)

// 获取计费规则列表
const getRuleList = async () => {
  const res = await getRuleListAPI(params.value)
  ruleList.value = res.data.rows
  total.value = res.data.total
}
getRuleList()

// 计费规则
const chargeTypeMap = new Map<Rule['chargeType'], string>([
  // [key, value] 键值对
  ['duration', '时长收费'],
  ['turn', '按次收费'],
  ['partition', '分段消费']
]);

const exportToExcel = () => {
  // 创建工作簿
  const workbook = utils.book_new()
  // 创建工作表(Join转工作表)
  const worksheet = utils.json_to_sheet(ruleList.value.map((item, index) => ({
    ...item,
    id: index + 1,
    chargeType: chargeTypeMap.get(item.chargeType)
  })))
  // 在xlsx文件夹添加工作表,Data为工作表名称
  utils.book_append_sheet(workbook, worksheet, '计费规则')
  // 覆盖默认表头(在工作表,二维数组,表头坐标)
  utils.sheet_add_aoa(worksheet, [
    ['序号', '计费规则','计费规则名称','免费时长(分钟)','收费上限(元)','计费方式','计费规则']
  ],
    { origin: 'A1' }
  )
  // 导入下载xlxs文件
  writeFileXLSX(workbook,'计费规则表.xlsx')
}
</script>

<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary">增加停车计费规则</el-button>
      <el-button @click="exportToExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column label="计费规则编号" prop="ruleNumber" />
        <el-table-column label="计费规则名称" prop="ruleName" />
        <el-table-column label="免费时长(分钟)" prop="freeDuration" />
        <el-table-column label="收费上限(元)" prop="chargeCeiling" />
        <el-table-column label="计费方式">
          <template #default="{ row }">
            {{ chargeTypeMap.get(row.chargeType) }}
          </template>
        </el-table-column>
        <el-table-column label="计费规则" prop="ruleNameView" width="320" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default>
            <el-button size="small" type="primary" link>编辑</el-button>
            <el-button size="small" type="primary" link>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>